<?php

/**
 * Created by PhpStorm.
 * User: caohejie
 * Date: 2018/11/6
 * Time: 09:34
 */
class ff
{
    /**
     * mp4文件地址
     * @var string
     */
    public $mp4path;

    /**
     * 多长时间一个包
     * @var int
     */
    public $pack_len = 3;

    /**
     * 每秒取几帧
     * @var int
     */
    public $sec_zhen = 20;

    /**
     * 总共生成几个包
     * @var int
     */
    public $pack_num = 5;

    /**
     * 包生成间隔
     * @var
     */
    public $jiange;

    /**
     * MP4文件时长
     * @var
     */
    public $filetime;


    public function __construct($mp4path)
    {
        $this->mp4path = $mp4path;
    }

    /**
     * 多长时间截取一个包生成gif图片
     */
    public function setJiange()
    {

        $this->jiange = floor($this->filetime / $this->pack_num);

    }

    /**
     * 获取mp4文件时长
     */
    public function getFiletime()
    {
        $vtime = shell_exec("ffmpeg -i " . $this->mp4path . " 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//");//总长度
        $duration = explode(":", $vtime);
        $duration_in_seconds = $duration[0] * 3600 + $duration[1] * 60 + round($duration[2]);//转化为秒
        $this->filetime = $duration_in_seconds;

    }

    /**
     * 生成图片
     * @param $start_sen 开始时间
     * @param $sen  取多少秒
     */
    public function getImage($start_sen, $sen)
    {
        $this->deldir("./img/pic/");
        if (!file_exists("./img/pic")) {
            mkdir("./img/pic", 0777, true);
        }

        shell_exec("ffmpeg -ss " . $start_sen . " -i " . $this->mp4path . " -y -f image2 -r 1  -t " . $sen . " -s 352x240 ./img/pic/" . "" . "%03d.jpg 1>/dev/null 2>&1");
    }

    /**
     *获取用于生成gif的图片
     */
    public function getImageForGif()
    {
        for ($i = 1; $i < $this->pack_num; $i++) {

            $filename = __DIR__ . "/img/" . $i . "/";

            $this->deldir($filename);

            if (!file_exists($filename)) {
                mkdir($filename, 0777, true);
            }

            //echo "ffmpeg -ss " . $i * $this->jiange . " -i " . $this->mp4path . " -y -f image2 -r " . $this->sec_zhen . "  -t " . $this->pack_len . " -s 100x80 ./img/" . $i . "/" . "" . "%03d.jpg 1>/dev/null 2>&1" . PHP_EOL;

            shell_exec("ffmpeg -ss " . $i * $this->jiange . " -i " . $this->mp4path . " -y -f image2 -r " . $this->sec_zhen . "  -t " . $this->pack_len . "  ./img/" . $i . "/" . "" . "%03d.jpg 1>/dev/null 2>&1");

            if ($i != 1) {
                //获取当前目录下的图片
                $res = $this->get_files_by_ext($filename, "jpg");

                foreach ($res as $key => $val) {
                    $res = explode(".", $val);
                    $res = $this->dispRepair($this->quling($res[0]) + (($i - 1) * $this->pack_len * $this->sec_zhen));
                    rename("./img/" . $i . "/" . $val, "./img/" . $i . "/" . $res . ".jpg");
                    copy("./img/" . $i . "/" . $res . ".jpg", "./img/1/" . $res . ".jpg");
                }

            }
        }

    }

    /**
     * 生成gif
     * @param int $zhenshu gif每秒多少帧
     */
    public function makeGif($zhenshu = 25)
    {

        unlink("./img/all.gif");
        shell_exec("ffmpeg -f image2 -y -framerate " . $zhenshu . " -i ./img/1/%03d.jpg ./img/all.gif 1>/dev/null 2>&1");

    }

    /**
     *
     */
    public function makeFilm()
    {
        shell_exec("ffmpeg -f image2 -i ./img/1/%03d.jpg -b:v 200k -vcodec libx264  -r " . $this->sec_zhen . " -s 480x360 -acodec libfaac -y ./img/all.mp4");

    }

    /**
     * 获取指定目录下只能扩展名的文件
     * @param $path
     * @param $ext
     * @return array
     */
    public function get_files_by_ext($path, $ext)
    {

        $files = array();

        if (is_dir($path)) {
            $handle = opendir($path);
            while ($file = readdir($handle)) {
                if ($file[0] == '.') {
                    continue;
                }
                if (is_file($path . $file) and preg_match('/\.' . $ext . '$/', $file)) {
                    $files[] = $file;
                }
            }
            closedir($handle);
            sort($files);
        }

        return $files;

    }

    /**
     * 补位
     * @param $str 原始字符串
     * @param int $len 总长度
     * @param int $msg 用于补位的字符
     * @param string $type 左补位还是右补位 默认左补位
     * @return string
     */
    public function dispRepair($str, $len = 3, $msg = 0, $type = '1')
    {
        $length = $len - strlen($str);
        if ($length < 1) return $str;
        if ($type == 1) {
            $str = str_repeat($msg, $length) . $str;
        } else {
            $str .= str_repeat($msg, $length);
        }
        return $str;
    }

    /**
     * 取出补位用的0
     * @param $name
     * @return mixed
     */
    public function quling($name)
    {
        for ($i = 0; $i < strlen($name); $i++) {

            //循环一次，指针向右移动一次

            $newUser[$i] = substr($name, $i, 4);

            //如果被截取的第一个数为零，则将零换为空

            if (0 == substr($newUser[$i], 0, 1)) {

                $newUserName[$i] = str_replace(0, "", $newUser[$i]);

            } else {

                //循环结束，跳出循环

                return $newUser[$i];


            }

        }

    }

    /**
     * 删除目录和目录下面的所有文件
     * @param $path
     */
    function deldir($path)
    {
        //如果是目录则继续
        if (is_dir($path)) {
            //扫描一个文件夹内的所有文件夹和文件并返回数组
            $p = scandir($path);
            foreach ($p as $val) {
                //排除目录中的.和..
                if ($val != "." && $val != "..") {
                    //如果是目录则递归子目录，继续操作
                    if (is_dir($path . $val)) {
                        //子目录中操作删除文件夹和文件
                        deldir($path . $val . '/');
                        //目录清空后删除空文件夹
                        @rmdir($path . $val . '/');
                    } else {
                        //如果是文件直接删除
                        unlink($path . $val);
                    }
                }
            }
        }
        @rmdir($path);
    }

    public function clearFile()
    {

        for ($i = 1; $i < $this->pack_num; $i++) {
            $filename = __DIR__ . "/img/" . $i . "/";
            $this->deldir($filename);
        }

    }


}